<template>
  <el-container class="workbench-container">
    <el-header height="60px" class="workbench-header">
      <div class="header-left">
        <div class="logo-area" @click="goHome">
          <el-icon :size="24" color="#409eff"><DataAnalysis /></el-icon>
          <span class="app-title">数据分析工作台</span>
        </div>
        
        <el-divider direction="vertical" />

        <!-- Case Info -->
        <div class="case-info" v-if="currentCase">
          <span class="label">当前案件：</span>
          <el-tag effect="plain" type="primary">{{ currentCase.case_name || currentCase.name }}</el-tag>
          <el-button type="primary" link icon="Switch" @click="showCaseSwitcher" size="small" style="margin-left: 10px">
            切换
          </el-button>
        </div>
      </div>

      <div class="header-right">
        <el-menu 
          mode="horizontal" 
          :ellipsis="false" 
          class="nav-menu"
        >
          <!-- Data Management -->
          <el-sub-menu index="data">
            <template #title>
              <el-icon><Database /></el-icon>数据管理
            </template>
            <el-menu-item index="data-import" @click="openTab('import')">
               <el-icon><Upload /></el-icon>数据导入
            </el-menu-item>
            <el-menu-item index="data-warehouse" @click="openTab('data-view')">
               <el-icon><Files /></el-icon>数据仓库
            </el-menu-item>
            <el-menu-item index="template" @click="openTab('template')">
               <el-icon><List /></el-icon>模版管理
            </el-menu-item>
          </el-sub-menu>

          <!-- Analysis -->
          <el-sub-menu index="analysis">
            <template #title>
              <el-icon><Cpu /></el-icon>智能分析
            </template>
            <el-menu-item index="algo-analysis" @click="openTab('analysis')">
               <el-icon><Cpu /></el-icon>智能分析中心
            </el-menu-item>
            <el-menu-item index="funds-analysis" @click="openTab('funds-analysis')">
               <el-icon><Money /></el-icon>资金穿透分析
            </el-menu-item>
            <el-menu-item index="profile" @click="openTab('profile')">
               <el-icon><User /></el-icon>情报研判
            </el-menu-item>
          </el-sub-menu>

          <!-- Tools -->
          <el-menu-item index="tools" @click="openTab('tools')">
             <el-icon><Tools /></el-icon>辅助工具
          </el-menu-item>
        </el-menu>

        <el-button @click="toggleAIChat" circle title="AI 助手">
            <template #icon>
                <el-icon :color="showAIChat ? '#409eff' : ''"><Cpu /></el-icon>
            </template>
        </el-button>
        <el-divider direction="vertical" />
        
        <el-button @click="goHome" icon="HomeFilled" circle title="返回首页"></el-button>
      </div>
    </el-header>

    <div class="main-layout-wrapper" style="display: flex; flex: 1; overflow: hidden;">
        <el-main class="workbench-main">
           <el-tabs 
              v-model="currentTabId" 
              type="card" 
              closable 
              @tab-remove="closeTab"
              class="main-tabs"
           >
              <el-tab-pane
                v-for="tab in tabs"
                :key="tab.id"
                :label="tab.title"
                :name="tab.id"
                :closable="tab.closable"
              >
                 <keep-alive>
                   <component :is="tab.component" v-bind="tab.props" :key="tab.id"></component>
                 </keep-alive>
              </el-tab-pane>
           </el-tabs>
        </el-main>
        
        <!-- AI Chat Sidebar -->
        <div v-show="showAIChat" class="ai-sidebar" style="width: 350px; border-left: 1px solid #dcdfe6;">
            <AIChatPanel @close="showAIChat = false" />
        </div>
    </div>

    <!-- Case Selector Dialog -->
    <CaseSelectorDialog 
      v-model="caseSelectorVisible"
      :cases="caseStore.cases"
      :initialCaseId="currentCaseId"
      :disable-closed="currentTabId === 'import'"
      @confirm="handleCaseSelected"
    />
  </el-container>
</template>

<script setup>
import { ref, computed, onMounted, markRaw, provide, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useCaseStore } from '../stores/case'
import { 
    DataAnalysis, Coin as Database, Upload, Files, List, Cpu, Money, User, Tools, 
    Switch, HomeFilled 
} from '@element-plus/icons-vue'
import CaseSelectorDialog from '../components/common/CaseSelectorDialog.vue'

// Import components
import Dashboard from './workbench/Dashboard.vue'
import DataImport from './workbench/DataImport.vue'
import DataWarehouse from './workbench/DataWarehouse.vue'
import TemplateManage from './workbench/TemplateManage.vue'
import Analysis from './workbench/Analysis.vue'
import IntelligenceCenter from './workbench/IntelligenceCenter.vue'
import FundsAnalysis from './workbench/FundsAnalysis.vue'
import ToolsView from './workbench/Tools.vue'
import AIChatPanel from './workbench/AIChatPanel.vue'

// Router and store
const router = useRouter()
const route = useRoute()
const caseStore = useCaseStore()

const currentCase = ref(null)
const currentCaseId = ref(null)
const caseSelectorVisible = ref(false)
const showAIChat = ref(false)

const toggleAIChat = () => {
    showAIChat.value = !showAIChat.value
}

// Provide case context
provide('currentCase', computed(() => currentCase.value))
provide('currentCaseId', computed(() => currentCaseId.value))
provide('showCaseSwitcher', () => showCaseSwitcher())

// Tab System
const tabs = ref([
  { id: 'dashboard', title: '工作台首页', component: markRaw(Dashboard), closable: false }
])
const currentTabId = ref('dashboard')

onMounted(async () => {
    // Load case info
    const caseId = route.query.caseId
    if (caseId) {
        if (caseStore.cases.length === 0) {
            await caseStore.fetchCases()
        }
        currentCase.value = caseStore.cases.find(c => c.id == caseId)
        if (currentCase.value) {
            currentCaseId.value = currentCase.value.id
        }
    } else {
        // Force selector if no case
        // But delay slightly to let app init
        setTimeout(() => { showCaseSwitcher() }, 500)
    }

    // Handle initial tab
    const initialTab = route.query.tab
    if (initialTab) openTab(initialTab)
})

// Watch case changes
watch(() => route.query.caseId, (newCaseId) => {
    if (newCaseId && newCaseId != currentCaseId.value) {
        const foundCase = caseStore.cases.find(c => c.id == newCaseId)
        if (foundCase) {
            currentCase.value = foundCase
            currentCaseId.value = foundCase.id
        }
    }
})

const goHome = () => router.push('/cases')

const openTab = (type, props = {}) => {
  let tabId = type
  let title = ''
  let component = null
  
  switch (type) {
    case 'import': title = '数据导入'; component = DataImport; break;
    case 'data-view': title = '数据仓库'; component = DataWarehouse; break;
    case 'template': title = '模版管理'; component = TemplateManage; break;
    case 'analysis': title = '智能分析'; component = Analysis; break;
    case 'funds-analysis': title = '资金穿透'; component = FundsAnalysis; break;
    case 'profile': title = '情报研判'; component = IntelligenceCenter; break;
    case 'tools': title = '辅助工具'; component = ToolsView; break;
    default: return;
  }
  
  const existingTab = tabs.value.find(t => t.id === tabId)
  if (existingTab) {
    currentTabId.value = tabId
  } else {
    tabs.value.push({
      id: tabId,
      title,
      component: markRaw(component),
      props,
      closable: true
    })
    currentTabId.value = tabId
  }
}

const closeTab = (targetName) => {
  const tabsList = tabs.value
  let activeName = currentTabId.value
  
  if (activeName === targetName) {
    tabsList.forEach((tab, index) => {
      if (tab.id === targetName) {
        const nextTab = tabsList[index + 1] || tabsList[index - 1]
        if (nextTab) {
          activeName = nextTab.id
        }
      }
    })
  }
  
  currentTabId.value = activeName
  tabs.value = tabsList.filter(tab => tab.id !== targetName)
}

const showCaseSwitcher = async () => {
    if (caseStore.cases.length === 0) await caseStore.fetchCases()
    caseSelectorVisible.value = true
}

const handleCaseSelected = (selectedCase) => {
    currentCase.value = selectedCase
    currentCaseId.value = selectedCase.id
    router.push({ path: route.path, query: { ...route.query, caseId: selectedCase.id } })
}
</script>

<style scoped>
.workbench-container {
  height: 100vh;
  background-color: #f5f7fa;
}

.workbench-header {
  background: white;
  border-bottom: 1px solid #dcdfe6;
  display: flex !important;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.logo-area {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
}

.app-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.case-info {
    font-size: 14px;
    display: flex;
    align-items: center;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 15px;
}

.nav-menu {
    border-bottom: none !important;
    background: transparent;
}

:deep(.el-menu--horizontal > .el-menu-item), 
:deep(.el-menu--horizontal > .el-sub-menu .el-sub-menu__title) {
    height: 60px;
    line-height: 60px;
    border-bottom: none;
    color: #606266;
}

:deep(.el-menu--horizontal > .el-menu-item.is-active), 
:deep(.el-menu--horizontal > .el-sub-menu.is-active .el-sub-menu__title) {
    color: #409eff !important;
    border-bottom: 2px solid #409eff !important;
}

.workbench-main {
    padding: 0 !important;
    overflow: hidden !important;
    display: flex;
    flex-direction: column;
}

.main-tabs {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 100%;
}

:deep(.el-tabs__header) {
    margin: 0 !important;
    background: white;
    padding: 6px 10px 0;
}

:deep(.el-tabs__content) {
    flex: 1;
    overflow: hidden;
    padding: 15px; /* Add some padding to content area */
    background: #f0f2f5;
}

:deep(.el-tab-pane) {
    height: 100%;
    background: white;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0,0,0,0.05);
    overflow: hidden; /* Prevent spillover */
}
</style>
